<template>
<div>
    <Row v-if="development">
        <span>显示模式</span>
        <Select v-model="selected_mode" style="width:200px">
            <Option v-for="(item, key) in modes" :value="key" :key="key">{{ item }}</Option>
        </Select>
    </Row>
    <Row v-if="selected_mode!='edit'&&process.steps.length==0">
        <Col span="24">
            <span style="color:red">未设置流程</span>
        </Col>
    </Row>
    <Row v-if="selected_mode=='edit'" style="padding:5px">
        <Button type="primary" icon="ios-list-outline" @click="refreshStepTemplateList();select_modal.show=true">选择模板</Button>
        <Button type="primary" icon="ios-plus-outline" @click="save_modal.show=true">保存成模板</Button>
    </Row>
    <Row v-if="selected_mode=='edit'" :gutter="16">
        <Col span="12">
            <div v-for="(item, index) in process.steps" :key="index">
                <Button shape="circle" :type="step_name==index.toString()?'primary':'ghost'" style="padding:5px;width:30px;">{{index+1}}</Button>
                <Button type="ghost" style="width:50%;" @click="showStepDetail(index)">{{item.title || "未命名"}}</Button>
                <Button shape="circle" @click="del(index)" icon="close-round" style="margin-left:5px;"></Button>
                <Button shape="circle" @click="next(index)" icon="chevron-down" style="margin-left:5px;" :disabled="index == process.steps.length - 1"></Button>
                <Button shape="circle" @click="pre(index)" icon="chevron-up" style="margin-left:5px;" :disabled="index == 0"></Button>
            </div>
            <Button type="primary" @click="handleAdd()">添加流程步骤</Button>
            <div v-if="false">
                <div>流程结束显示标题:</div>
                <Input v-model="process.finished_title" type="text" placeholder="请输入流程结束显示标题"></Input>
                <div>流程结束显示内容:</div>
                <Input v-model="process.finished_content" type="textarea" :autosize="{minRows: 3,maxRows: 10}" placeholder="请输入流程结束显示内容"></Input>
            </div>
        </Col>
        <Col span="12">
            <Collapse v-if="process.steps.length>0" v-model="step_name" accordion>
                <Panel v-for="(item, index) in process.steps" :name="''+index">
                    {{item.title}}
                    <div slot="content">
                        <Tabs process="name1">
                            <TabPane v-if="!item.is_modifing" label="介绍" name="name1">
                                <Form :label-width="50">
                                    <FormItem label="内容">
                                        <div>{{item.remark}}</div>
                                    </FormItem>
                                    <FormItem label="附件">
                                        <p v-for="appendix in item.appendix"><a :href="appendix.url">{{appendix.name}}</a></p>
                                    </FormItem>
                                </Form>
                                <Row style="margin-top:10px">
                                    <Col span="24" style="text-align:center">
                                        <Button type="warning" @click="handleStepModify(item)">修改</Button>
                                    </Col>
                                </Row>
                            </TabPane>
                            <TabPane v-if="item.is_modifing" label="介绍" name="name1">
                                <Form :label-width="50">
                                    <FormItem label="名称">
                                        <Input type="text" v-model="item.title" placeholder="请输入步骤名称"></Input>
                                    </FormItem>
                                    <FormItem label="内容">
                                            <Input v-model="item.remark" type="textarea" :autosize="{minRows: 3,maxRows: 10}" placeholder="请输入备注等内容"></Input>
                                    </FormItem>
                                    <FormItem label="设置">
                                        <Row>
                                            <Col span="24">
                                                <Checkbox v-model="item.allow_demand_upload">允许需求方上传文件</Checkbox>
                                                <Checkbox v-model="item.allow_checking_modify">允许审核时修改</Checkbox>
                                            </Col>
                                        </Row>
                                    </FormItem>
                                    <FormItem label="附件">
                                            <UploadedList  v-model="item.appendix" :format="['doc','docx','pdf']"></UploadedList>
                                    </FormItem>
                                </Form>
                                <Row style="margin-top:10px">
                                    <Col span="24" style="text-align:center">
                                        <Button type="primary" @click="handleStepData(item)">保存</Button>
                                    </Col>
                                </Row>
                            </TabPane>
                        </Tabs>
                    </div>
                </Panel>
            </Collapse>
        </Col>
    </Row>
    <div v-if="process.steps.length>0">
        <Row v-if="selected_mode=='preview_default'||selected_mode=='preview_all'" :gutter="6">
            <Col span="6">
                <Steps direction="vertical" :current="process.current">
                    <Step v-for="(item, index) in full_steps" :title="item.title">
                        <p v-if="index<full_steps.length-1">
                            <Button type="ghost" shape="circle" size="small"  @click="showStepDetail(index)">查看详情</Button>
                        </p>
                    </Step>
                </Steps>
            </Col>
            <Col span="18">
                <Collapse v-if="process.steps.length>0" v-model="step_name" @on-change="handleCollapseOnChange" accordion>
                    <Panel v-for="(item, index) in process.steps" :name="''+index" :key="''+index">
                        {{item.title}}
                        <div slot="content">
                            <Tabs process="name1">
                                <TabPane label="介绍" name="name1">
                                    <Form :label-width="50">
                                        <FormItem label="内容">
                                            <div>{{item.remark}}</div>
                                        </FormItem>
                                        <FormItem label="附件">
                                            <p v-for="appendix in item.appendix"><a :href="appendix.url">{{appendix.name}}</a></p>
                                        </FormItem>
                                    </Form>
                                </TabPane>
                                <TabPane v-if="selected_mode=='preview_all'" label="服务方材料" name="name2">
                                    <Form :label-width="50">
                                        <FormItem label="备注">
                                            <div>{{item.service_remark}}</div>
                                        </FormItem>
                                        <FormItem label="附件">
                                            <p v-for="appendix in item.service_appendix"><a :href="appendix.url">{{appendix.name}}</a></p>
                                        </FormItem>
                                    </Form>
                                </TabPane>
                                <TabPane v-if="selected_mode=='preview_all'" label="需求方材料" name="name3">
                                    <Form :label-width="50">
                                        <FormItem label="备注">
                                            <div>{{item.demand_remark}}</div>
                                        </FormItem>
                                        <FormItem v-if="item.allow_demand_upload" label="附件">
                                            <p v-for="appendix in item.demand_appendix"><a :href="appendix.url">{{appendix.name}}</a></p>
                                        </FormItem>
                                    </Form>
                                </TabPane>
                            </Tabs>
                        </div>
                    </Panel>
                </Collapse>
            </Col>
        </Row>
        <Row v-if="selected_mode=='service'">
            <Card :dis-hover="true">
                <Steps :current="process.current">
                    <Step v-for="(item, index) in full_steps" :title="item.title"></Step>
                </Steps>
            </Card>
            <div>
                <div v-if="is_finished" style="margin-bottom:1em">
                    <Card :dis-hover="true" v-if="is_finished" style="text-align:center;font-size:24px;color:green">
                        <p><Icon type="checkmark-circled" :size="50"></Icon></p>
                        <span>流程结束</span>
                    </Card>
                </div>
                <div v-if="!is_finished">
                    <Card :bordered="false" :dis-hover="true">
                        <p slot="title">介绍</p>
                        <Form :label-width="50">
                            <FormItem label="内容">
                                <div>{{current.remark}}</div>
                            </FormItem>
                            <FormItem label="附件">
                                <p v-for="appendix in current.appendix"><a :href="appendix.url">{{appendix.name}}</a></p>
                            </FormItem>
                        </Form>
                    </Card>
                    <Card :bordered="false" :dis-hover="true">
                        <p slot="title">需求方提交材料<span style="color:#888">（需求方按照要求提交的材料）</span></p>
                        <Form :label-width="50">
                            <div v-if="process.status==1" style="color:red">需求方有新提交！</div>
                            <FormItem label="备注">
                                <div>{{current.demand_remark}}</div>
                            </FormItem>
                            <FormItem label="附件">
                                <p v-for="appendix in current.demand_appendix"><a :href="appendix.url">{{appendix.name}}</a></p>
                            </FormItem>
                        </Form>
                    </Card>
                    <Card :bordered="false" :dis-hover="true">
                        <p slot="title">我方提交材料<span style="color:#888">（我方需要提供给需求方的材料）</span></p>
                        <Form :label-width="50">
                            <FormItem label="备注">
                                <Input v-model="current.service_remark" type="textarea" :autosize="{minRows: 3,maxRows: 10}" placeholder="请输入备注等内容"></Input>
                            </FormItem>
                            <FormItem label="附件">
                                <UploadedList  v-model="current.service_appendix" :format="['doc','docx','pdf']"></UploadedList>
                            </FormItem>
                        </Form>
                    </Card>
                </div>
                <Row>
                    <Col span="18" offset="3">
                        <RadioGroup v-model="radio_value" vertical>
                            <Radio label="0" :disabled="is_finished">保存当前数据，停留在当前步骤</Radio>
                            <Radio label="1" :disabled="is_finished">审核通过，进入下一步</Radio>
                            <Radio label="2" :disabled="is_finished">审核不通过（需要注明原因）</Radio>
                            <Radio label="3" :disabled="process.current==0">历史步骤存在问题，返回上一步</Radio>
                        </RadioGroup>
                        <Input v-if="!is_finished&&radio_value==2" v-model="process.failed_reason" type="textarea" :autosize="{minRows: 3,maxRows: 10}" placeholder="请输入驳回原因"></Input>
                    </Col>
                </Row>
                <Row style="margin-top:30px">
                    <Col span="24" style="text-align:center">
                        <Button type="primary" @click="handleStepServiceData()" :disabled="radio_value=='-1'||(radio_value=='2'&&process.failed_reason.trim()=='')">确认</Button>
                    </Col>
                </Row>
            </div>
        </Row>
        <Row v-if="selected_mode=='demand'">
            <Card :dis-hover="true">
                <Steps :current="process.current">
                    <Step v-for="(item, index) in full_steps" :title="item.title"></Step>
                </Steps>
            </Card>
            <Card :bordered="false" :dis-hover="true" v-if="is_finished" style="text-align:center;font-size:24px;color:green">
                <p><Icon type="checkmark-circled" :size="50"></Icon></p>
                <span>{{process.finished_content}}</span>
            </Card>
            <div v-if="!is_finished">
                <Card :bordered="false" :dis-hover="true" v-if="process.status==1" style="text-align:center;font-size:24px;color:orange">
                    <p><Icon type="load-d" :size="50"></Icon></p>
                    <span>正在审核，请耐心等待！{{current.allow_checking_modify?"审核阶段允许您修改提交内容!":""}}</span>
                </Card>
                <Card :bordered="false" :dis-hover="true" v-if="process.status==2" style="text-align:center;font-size:24px;color:red">
                    <p><Icon type="close-circled" :size="50"></Icon></p>
                    <span>审核失败：{{process.failed_reason}}</span>
                    <Button type="primary" @click="handleReCheck()">申请重新审核</Button>
                </Card>
                <div v-if="process.status!=2">
                    <Card :bordered="false" :dis-hover="true">
                        <p slot="title">介绍</p>
                        <Form :label-width="50">
                            <FormItem label="内容">
                                <div>{{current.remark}}</div>
                            </FormItem>
                            <FormItem label="附件">
                                <p v-for="appendix in current.appendix"><a :href="appendix.url">{{appendix.name}}</a></p>
                            </FormItem>
                        </Form>
                    </Card>
                    <Card :bordered="false" :dis-hover="true">
                        <p slot="title">服务方提交材料<span style="color:#888">（服务方按照要求提交的材料）</span></p>
                        <Form :label-width="50">
                            <FormItem label="备注">
                                <div>{{current.service_remark}}</div>
                            </FormItem>
                            <FormItem label="附件">
                                <p v-for="appendix in current.service_appendix"><a :href="appendix.url">{{appendix.name}}</a></p>
                            </FormItem>
                        </Form>
                    </Card>
                    <Card :bordered="false" :dis-hover="true">
                        <p slot="title">我方提交材料<span style="color:#888">（我方需要提供给服务方的材料）</span></p>
                        <Form v-if="process.status==0||process.status==-1||current.allow_checking_modify" :label-width="50">
                            <FormItem label="备注">
                                <Input v-model="current.demand_remark" type="textarea" :autosize="{minRows: 3,maxRows: 10}" placeholder="请输入备注等内容"></Input>
                            </FormItem>
                            <FormItem v-if="current.allow_demand_upload" label="附件">
                                <UploadedList  v-model="current.demand_appendix" :format="['doc','docx','pdf']"></UploadedList>
                            </FormItem>
                            <Row style="margin-top:30px">
                                <Col span="24" style="text-align:center">
                                    <Button type="primary" @click="handleStepDemandData()">提交</Button>
                                </Col>
                            </Row>
                        </Form>
                        <Form v-if="process.status==1&&!current.allow_checking_modify" :label-width="50">
                            <FormItem label="备注">
                                <div>{{current.demand_remark}}</div>
                            </FormItem>
                            <FormItem label="附件">
                                <p v-for="appendix in current.demand_appendix"><a :href="appendix.url">{{appendix.name}}</a></p>
                            </FormItem>
                        </Form>
                    </Card>
                </div>
            </div>
        </Row>
        <Row v-if="selected_mode=='preview_list'">
            <div v-for="(item,key) in process.steps" style="margin-left:10px;">
                <span style="color:#19be6b;">步骤{{key+1}}: {{item.title}} </span><br>
                <span style="color:#ff9900;margin-left:5px;">1、要求：</span>{{item.remark}}<br>
                <span style="color:#ff9900;margin-left:5px;">2、附件：</span>
                <p v-for="(process,index) in item.appendix">
                    <a :href="process.url">（{{index+1}}）、{{process.name}}</a>
                </p>
            </div>
        </Row>
    </div>
    <Modal v-model="save_modal.show" title="保存为模板" :loading="save_modal.loading" :transfer="false">
        <Form ref="save_modal" :model="save_modal.form.data" :rules="save_modal.form.rules" :label-width="80">
            <FormItem label="模板名称" prop="title">
                <Input v-model="save_modal.form.data.title" placeholder="请输入模板名称"></Input>
            </FormItem>
        </Form>
        <div slot="footer">
            <Button type="text" size="large" @click="save_modal.show=false">取消</Button>
            <Button type="primary" size="large" @click="handleSaveTemplate()">保存</Button>
        </div>
    </Modal>
    <Modal v-model="select_modal.show" title="选择模板" :loading="select_modal.loading" :transfer="false">
        <Table border :columns="select_modal.table.columns" :data="select_modal.table.data"></Table>
        <div slot="footer">
            <Button type="text" size="large" @click="select_modal.show=false">取消</Button>
        </div>
    </Modal>
</div>
</template>
<script>
import UploadedList from '@/common/components/UploadedList.vue'
import Step from '@/common/model/Step'

export default {
    name: 'StepsEditor',
    props: {
        source: {
            type: Object
        },
        sourceType: { // service, abutment
            type: String
        },
        mode:{
            type: String,
            default: "preview_default"
        }
    },
    components:{
        UploadedList
    },
    data() {
        return {
            development: false, // 当前是否为开发模式
            selected_mode: 'edit',
            modes: {
                edit: "编辑",
                demand: "需求方",
                service: "服务方",
                preview_default: "预览默认",
                preview_list: "预览清单",
                preview_all: "预览所有"
            },
            save_modal: {
                show: false,
                loading: false,
                form: {
                    rules: {
                        title: { required: true, message: '模板名称不能为空', trigger: 'blur' }
                    },
                    data: {
                        title: ""
                    }
                }
            },
            select_modal: {
                show: false,
                loading: false,
                table: {
                    columns: [
                        { title: '模板编号', key: "id" },
                        { title: '模板名称', key: "name" },
                        { title: '操作', align: 'center', render: (h, params) => {
                            return h("div", [
                                h('Button', {
                                    style: { marginRight: "5px" },
                                    props: { type: 'success', size: 'small' },
                                    on: { click: () => { this.handleSelectTemplate(params); } }
                                }, '应用'),
                                h('Button', {
                                    props: { type: 'error', size: 'small' },
                                    on: { click: () => { this.handleDeleteTemplate(params); } }
                                }, '删除')
                            ]);
                        } },
                    ],
                    data: []
                }
            },
            step_name: "0",
            radio_value: "-1",
            service_id: 0,
            abutment_id: 0,
            process: {
                service_member_id: 0,
                demand_member_id: 0,
                steps: [], 
                current: 0,
                finished_title: "已完成",
                finished_content: "已完成",
                status: 0,
                failed_reason: ""
            }
        }
    },
    computed: {
        source_type() {
            return this.sourceType;
        },
        current() {
            return this.process.steps[this.process.current];
        },
        full_steps() {
            var temp = this.process.steps.slice();
            temp.push({
                title: this.process.finished_title
            });
            return temp;
        },
        is_finished() {
            return this.process.current == this.process.steps.length;
        }
    },
    methods:{
        handleCollapseOnChange(key) {
            this.setCurrentStep(parseInt(key));
            this.getStepData(this.current);
        },
        handleSaveTemplate() {
            this.$refs["save_modal"].validate((valid) => {
                if (valid) {
                    this.save_modal.loading = true;
                    this.api.post("service_step_template/save", { service_id: this.service_id, name: this.save_modal.form.data.title }, res => {
                        this.$Message.success("保存成功");
                        this.save_modal.loading = false;
                        this.save_modal.show = false;
                        this.refreshStepTemplateList();
                    });
                }
            });
        },
        handleSelectTemplate(params) {
            this.api.post("service_step_template/copy", { id: params.row.id, service_id: this.service_id }, res => {
                this.$Message.success("应用模板成功");
                this.select_modal.show = false;
                this.refreshStepList();
            });
        },
        handleDeleteTemplate(params) {
            this.api.post("service_step_template/delete", { id: params.row.id }, res => {
                this.$Message.success("删除成功");
                this.select_modal.table.data.splice(params.index, 1);
            });
        },
        refreshStepTemplateList() {
            this.api.post("service_step_template/list", {exception:1}, res => {
                this.select_modal.table.data = res.list;
            });
        },
        refreshStepList() {
            this.api.post("service_step/get_steps", { service_id: this.service_id }, res => {
                this.source.steps = res.list;
                this.getData();
            });
        },
        handleAdd(){
            if(this.source_type=="service") {
                this.api.post("service_step/add", { service_id: this.service_id }, res => {
                    var step = new Step();
                    step.id = res.id;
                    this.process.steps.push(step);
                });
            }
        },
        del(index){
            if(this.source_type=="service") {
                this.api.post("service_step/delete", { id: this.process.steps[index].id, service_id: this.service_id }, res => {
                    this.process.steps.splice(index, 1);
                });
            }
        },
        pre(index){
            this.api.post("service_step/exchange", { id1: this.process.steps[index].id, id2: this.process.steps[index-1].id }, res => {
                var temp = this.process.steps[index];
                this.process.steps[index] = this.process.steps[index - 1];
                this.process.steps[index - 1] = temp;
                this.process.steps.push({});
                this.process.steps.pop();
            });
        },
        next(index){
            this.api.post("service_step/exchange", { id1: this.process.steps[index].id, id2: this.process.steps[index+1].id }, res => {
                var temp = this.process.steps[index];
                this.process.steps[index] = this.process.steps[index + 1];
                this.process.steps[index + 1] = temp;
                this.process.steps.push({});
                this.process.steps.pop();
            });
        },
        setCurrentStep(index){
            this.process.current = index;
            this.process.is_finished = this.is_finished;
            this.process.status = 0; // 设置步骤之后意味着服务方有了操作
            this.showStepDetail(index);
        },
        showStepDetail(index){
            this.step_name = ""+index;
            this.getStepData(this.process.steps[index]);
        },
        setCurrentMode() {
            this.selected_mode = this.mode;
        },
        formatprocess() {
            this.setCurrentMode();
            this.showStepDetail(this.process.current);
        },
        handleReject(value) {
            if(value) {
                this.process.status = 2;
            }else {
                this.process.status = 0;
            }
        },
        handleRadios(value) {
            this.radio_value = value;
        },
        handleReCheck() {
            this.process.status = 0;
        },
        handleStepModify(item) {
            item.is_modifing = true;
        },
        handleStepData(item) {
            if(this.abutment_id) return;
            this.api.post("service_step/modify", item.serialize(), res => {
                this.$Message.success("保存成功");
                item.is_modifing = false;
            });
        },
        handleStepServiceData() {
            if(!this.abutment_id) return;
            var current = this.process.current;
            switch(this.radio_value) {
                case "0": break;
                case "1": current = this.process.current + 1; break;
                case "2": break;
                case "3": current = this.process.current - 1; break;
            }
            var temp = this.current ? this.current.serialize() : {};
            this.api.post("service_step/set_step_service_data", { 
                id: temp.step_data_id, 
                remark: temp.service_remark, 
                appendix_ids: temp.service_appendix_ids, 
                abutment_id: this.abutment_id,
                is_finished: this.is_finished,
                status: this.process.status,
                failed_reason: this.process.failed_reason,
                step_number: current,
                service_member_id: this.process.service_member_id,
                demand_member_id: this.process.demand_member_id,
                exception: 1
            }, res => {
                this.$Modal.success({content: "提交成功" });
                this.setCurrentStep(current);
                this.setSource();
                this.radio_value = "-1";
                this.$emit("on-submit", this);
            });
        },
        handleStepDemandData() {
            if(!this.abutment_id) return;
            var temp = this.current.serialize();
            this.api.post("service_step/set_step_demand_data", { 
                id: temp.step_data_id, 
                remark: temp.demand_remark, 
                appendix_ids: temp.demand_appendix_ids,
                step_number: this.process.current,
                service_member_id: this.process.service_member_id,
                demand_member_id: this.process.demand_member_id
            }, res => {
                this.$Modal.success({content: "提交成功" });
                this.process.status = 1;
                this.setSource();
                this.$emit("on-submit", this);
            });
        },
        setSource() {
            this.source.step_abutment_data = {
                step_number: this.process.current,
                status: this.process.status,
                failed_reason: this.process.failed_reason
            }
        },
        getData() {
            this.process.steps = Step.parseList(this.source.steps || []);
            var sad = this.source.step_abutment_data || { step_number: 0, status: 0, failed_reason: "" };
            Object.assign(this.process, {
                current: sad.step_number,
                status: sad.status,
                failed_reason: sad.failed_reason
            });
            if(this.source_type == "service") {
                this.service_member_id = 0;
                this.demand_member_id = 0;
                this.abutment_id = 0;
                this.service_id = this.source.id;
            }else if(this.source_type == "abutment") {
                this.service_member_id = this.source.service_member_id;
                this.demand_member_id = this.source.demand_member_id;
                this.abutment_id = this.source.id;
                this.service_id = this.source.service_id;
            }
            this.radio_value = "-1";
            this.getStepData(this.current);
        },
        getStepData(step) {
            if(!step) return;
            if(!this.abutment_id) return;
            if(this.is_finished) return;
            this.api.post("service_step/get_step_data", { abutment_id: this.abutment_id, step_id: step.id }, res => {
                res.data.step_data_id = res.data.id;
                delete res.data.id;
                step.parse(res.data);
            });
        },
        showStatusModal() {
            if(this.selected_mode == "demand") {
                if(this.process.status == 2) {
                    //this.$Modal.info({content: "审核失败！" });
                }
            }else if(this.selected_mode == "service") {
                if(this.process.status == 2) {

                }
            }
        }
    },
    created() {
        this.getData();
        this.formatprocess();
    },
    watch: {
        "mode": "setCurrentMode",
        "process.current": "showStepDetail",
        "source.id": "getData"
    }
}
</script>
